'''
The MIT License (MIT)

Copyright (c) 2016 fatal_error

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

import httplib
from time import sleep
import time
from urllib import urlencode
from threading import Thread, Lock
import sys
from copy import deepcopy
from random import randint, uniform
from json import dumps, loads

SEND_DELAY = 3
READ_DELAY = 3

submit_address = '/data/post'
security_code = 'n427yd48r2guy34s'
headers = {'Content-type': 'application/x-www-form-urlencoded'}
watchers = ['Sunlight', 'Temperature', 'Dht11_Humanity', 'Gases', 'Human', 'Flame']

isTerminated = False
send_queue = []
lock = Lock()

def initDataSource():
    from serial import Serial
    dev = Serial('/dev/ttyACM0', 9600, timeout=1)
    dev.write(b'\n')
    k = readline()
    dev.write(b'open\n')
    dev.readline()
    return dev

def timeStamp():
    return int(time.time())

def combination(arr):
    earr = []
    length = len(arr)
    return_value = []
    for count in range(length):
        earr.append(False)
    for count in range(2**length - 1):
        for i in range(length):
            earr[i] = not earr[i]
            if earr[i] :
                break
        ladd = []
        for i in range(length):
            if earr[i] :
                ladd.append(arr[i])
        return_value.append(ladd)
    return return_value

def uni(a, b):
    return round(uniform(a, b), 2)

def generateRandomJSONData():
    a = {}
    a['sunlight'] = randint(10, 70)
    a['flame'] = randint(20, 90)
    a['temperature'] = randint(10, 95)
    a['gases'] = randint(10,95)
    a['timeStamp'] = timeStamp()
    a['human'] = randint(0,100) < 40
    return dumps(a)

def readFromSource(src):
    return_value = {}
    temp_value = {}
    for x in watchers:
        src.write(dumps({'watchers': [x]}) + '\n')
        return_value[x] = loads(src.readline().strip())[x]

def getConnection(host, port, strict):
    return httplib.HTTPConnection(host, port, strict)

def send(conn, data):
    body = urlencode({'code': security_code, 'submition': data})
    conn.request('POST', submit_address, body, headers)
    return conn.getresponse()

def readthr():
    global lock, send_queue, isTerminated
    src = initDataSource()
    while True:
        if isTerminated:
            break
        if lock.acquire():
            send_queue.append(readFromSource())
        lock.release()
        sleep(READ_DELAY)

def sendthr(host, port, strict, max_len=20, keep_len=1):
    global lock, send_queue, isTerminated
    t_send_queue = []
    conn = None
    
    while True:
        if isTerminated:
            break
        # If the network connection is closed due to failures occurred, then try to reset it.
        if conn == None:
            try:
                conn = getConnection(host, port, strict)
            except:
                sleep(SEND_DELAY)
                continue

        if lock.acquire():
            current_send_data = None
            try:
                while len(send_queue) > 0:
                    current_send_data = send_queue.pop()
                    send(conn, current_send_data)
                    print 'Sent: ' + current_send_data
            except:
                send_queue.append(current_send_data)
                conn.close()
                conn = None
                print 'Failed to send: ' + current_send_data + ', length of send_queue is: ' + str(len(send_queue))
        lock.release()
        sleep(SEND_DELAY)

def set_status():
    global isTerminated
    isTerminated = True

def main(host, port, strict):
    from signal import signal, SIGINT, SIGTERM
    signal(SIGINT, set_status)
    signal(SIGTERM, set_status)
    readingthread = Thread(target = readthr)
    readingthread.setDaemon(True)
    readingthread.start()
    sendthr(host, port, strict)


if __name__ == '__main__':
    v = sys.argv
    host = '127.0.0.1'
    port = 80
    strict = False
    for i in xrange(1, len(v)-1):
        if v[i] == '--port':
            port = int(v[i+1])
        if v[i] == '--host':
            host = v[i+1]
        if v[i] == '--strict':
            strict = True
    main(host, port, strict)
